package com.coldworks.coldjoke;

import java.util.Observable;
import java.util.Observer;

import com.coldworks.base.BaseFragment;
import com.coldworks.base.BaseFragmentActivity;
import com.coldworks.base.lib.menudrawer.MenuDrawer;
import com.coldworks.base.lib.menudrawer.MenuDrawer.PeekListener;
import com.coldworks.base.lib.menudrawer.MenuDrawer.DragMenuListener;
import com.coldworks.base.lib.menudrawer.MenuDrawerManager;
import com.coldworks.base.lib.menudrawer.MenuDrawerManager.CloseMenuListener;
import com.coldworks.base.lib.menudrawer.MenuDrawerManager.OpenMenuListener;
import com.coldworks.base.manager.BaseConfManager;
import com.coldworks.base.manager.BasePrefManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.R;
import com.coldworks.coldjoke.activity.LoginActivity;
import com.coldworks.coldjoke.activity.RegisterActivity;
import com.coldworks.coldjoke.activity.SettingActivity;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.manager.UserManager.UserStateSubject;
import com.coldworks.coldjoke.ui.MenuNavView;
import com.coldworks.coldjoke.ui.MenuNavView.OnNavSelectListner;
import com.coldworks.coldjoke.ui.PopWindowUtils;
import com.coldworks.coldjoke.ui.PopWindowUtils.OnItemSelected;
import com.coldworks.coldjoke.util.UrlUtil;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

public class MainActivity extends BaseFragmentActivity implements Observer,
		OnMenuShowListener {

	private static final String STATE_MENUDRAWER = "com.coldworks.coldjoke.MainActivity.menuDrawer";
	private static final String STATE_ACTIVE_POSITION = "com.coldworks.coldjoke.MainActivity.activePosition";
	private int mActivePosition = -1;
	private MenuDrawerManager mMenuDrawer;
	private MenuNavView navGroup;
	private LinearLayout menuContainer;
	private ImageButton settingsBtn;
	private PopupWindow menuLogin;
	private Button userName;
	private ImageView guide;

	private int versionCode;
	private BaseFragment currentfragment;
	private NavigationJokeFragment jokefragment;
	private NavigationJudgeFragment judgeFragment;
	private NavigationTopicFragment topicFragment;
	private NavigationPostJokeFragment postJokeFragment;
	private UserStateSubject userStateSubject;
	private boolean isLogin = false;

	@Override
	protected void onCreate(Bundle inState) {
		super.onCreate(inState);
		try {
			if (inState != null) {
				mActivePosition = inState.getInt(STATE_ACTIVE_POSITION);
			}
			userStateSubject = UserManager.getInstance().getUserStateSubject();
			userStateSubject.addObserver(this);
			initMenuView();
			jokefragment = new NavigationJokeFragment();
			judgeFragment = new NavigationJudgeFragment();
			topicFragment = new NavigationTopicFragment();
			postJokeFragment = new NavigationPostJokeFragment();
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.add(R.id.fragment_container, jokefragment);
			ft.commit();
			currentfragment = jokefragment;
			mMenuDrawer.setMenuDragEnabled(false);
			setUpViews();

			versionCode = BaseConfManager.getInstance().getVersionCode(context);
			if (versionCode > BasePrefManager.getInstance().getIntFromPrefs(
					context, BaseCONST.KEY.VERSION_CODE, 0)) {
				guide.setVisibility(ImageView.VISIBLE);
			}

			if (UserManager.getInstance().getIsAutoLogin()) {
				UserManager.getInstance().loginTask(context,
						UrlUtil.getLoginUrlFromLocal(), true);
			}

		} catch (Exception e) {
			log.info("", e);
		}
	}

	private void setUpViews() {
		userName = (Button) findViewById(R.id.user_name);
		guide = (ImageView) findViewById(R.id.guide);
		guide.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				guide.setVisibility(ImageView.GONE);
				BasePrefManager.getInstance().setIntToPrefs(context,
						BaseCONST.KEY.VERSION_CODE, versionCode);

			}
		});

		settingsBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this,
						SettingActivity.class));
			}
		});

		// 用户登陆后只显示用户的id
		userName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, LoginActivity.class));
			}
		});

		menuLogin = PopWindowUtils.MenuLoginView(context,
				onMenuLoginItemSelected);
	}

	/**
	 * 初始化菜单
	 */
	private void initMenuView() {
		mMenuDrawer = new MenuDrawerManager(this, MenuDrawer.MENU_DRAG_CONTENT);
		mMenuDrawer.setContentView(R.layout.navigation_main);
		menuContainer = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.menu_navigation_container, null);
		navGroup = (MenuNavView) menuContainer.findViewById(R.id.nav_group);
		settingsBtn = (ImageButton) menuContainer
				.findViewById(R.id.menu_setting);
		navGroup.setOnNavSelectListener(onNavSelectListner);
		mMenuDrawer.setMenuView(menuContainer);
		mMenuDrawer.getMenuDrawer().setTouchMode(
				MenuDrawer.TOUCH_MODE_FULLSCREEN);
		mMenuDrawer.setOnOpenMenuListener(openMenuListener);
		mMenuDrawer.setOnColseMenuListener(closeMenuListener);
		mMenuDrawer.getMenuDrawer().setOnPeekListener(peekListener);
		mMenuDrawer.getMenuDrawer().setOnDragMenuListener(dragMenuListener);

	}

	private DragMenuListener dragMenuListener = new DragMenuListener() {

		@Override
		public void onDragMenu(boolean isDragging) {
			if (isDragging) {
				// hideSoft();
			}
		}
	};

	private PeekListener peekListener = new PeekListener() {

		@Override
		public void onPeekEnd() {
			if (!mMenuDrawer.isMenuVisible() && currentfragment == jokefragment) {
				mMenuDrawer.setMenuDragEnabled(false);
			} else {
				mMenuDrawer.setMenuDragEnabled(true);
			}
		}

		@Override
		public void onPeekStart() {
			log.info("onPeekStart");
			// hideSoft();
		}
	};

	private OpenMenuListener openMenuListener = new OpenMenuListener() {

		@Override
		public void onOpenMenuStart() {

		}

		@Override
		public void onOpenMenuEnd() {
			mMenuDrawer.setMenuDragEnabled(true);

		}
	};

	private CloseMenuListener closeMenuListener = new CloseMenuListener() {

		@Override
		public void onCloseMenuStart() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onCloseMenuEnd() {
			if (currentfragment == jokefragment) {
				mMenuDrawer.setMenuDragEnabled(false);
			} else {
				mMenuDrawer.setMenuDragEnabled(true);
			}
		}
	};

	/**
	 * 菜单点击事件
	 */

	private OnNavSelectListner onNavSelectListner = new OnNavSelectListner() {

		@Override
		public void onNavTopicClick() {
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.replace(R.id.fragment_container, topicFragment);
			ft.addToBackStack(null);
			ft.commit();
			currentfragment = topicFragment;
			mMenuDrawer.setMenuDragEnabled(true);
			mMenuDrawer.closeMenu();
		}

		@Override
		public void onNavPostClick() {
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.replace(R.id.fragment_container, postJokeFragment);
			ft.addToBackStack(null);
			ft.commit();
			currentfragment = postJokeFragment;
			mMenuDrawer.setMenuDragEnabled(true);
			mMenuDrawer.closeMenu();
		}

		@Override
		public void onNavJudgeClick() {
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.replace(R.id.fragment_container, judgeFragment);
			ft.addToBackStack(null);
			ft.commit();
			currentfragment = judgeFragment;
			mMenuDrawer.setMenuDragEnabled(true);
			mMenuDrawer.closeMenu();
		}

		@Override
		public void onNavJokeClick() {
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.replace(R.id.fragment_container, jokefragment);
			ft.addToBackStack(null);
			ft.commit();
			currentfragment = jokefragment;
			mMenuDrawer.setMenuDragEnabled(false);
			mMenuDrawer.closeMenu();

		}

		@Override
		public void onNavClose() {
			mMenuDrawer.closeMenu();
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onRestoreInstanceState(Bundle inState) {
		super.onRestoreInstanceState(inState);
		mMenuDrawer.onRestoreDrawerState(inState
				.getParcelable(STATE_MENUDRAWER));
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelable(STATE_MENUDRAWER,
				mMenuDrawer.onSaveDrawerState());
		outState.putInt(STATE_ACTIVE_POSITION, mActivePosition);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (mMenuDrawer.isMenuVisible()) {
			mMenuDrawer.closeMenu();
			return true;
		}

		if (keyCode == KeyEvent.KEYCODE_MENU) {
			hideSoft();
			mMenuDrawer.openMenu();
		}

		if (keyCode != KeyEvent.KEYCODE_BACK || event.getRepeatCount() != 0) {
			return super.onKeyDown(keyCode, event);
		}
		// 捕获到返回键
		this.quitDialog();
		return true;
	}

	private void quitDialog() {
		new AlertDialog.Builder(context)
				.setMessage(getResources().getString(R.string.quit_message))
				.setPositiveButton(R.string.quit,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						})
				.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						}).create().show();
	}

	/**
	 * 注册到userStateSubject，用以改变菜单右下角的状态
	 */
	@Override
	public void update(Observable o, Object data) {
		UserStateSubject observable = (UserStateSubject) o;
		if (observable.getUserState() == UserManager.LOGINED) {
			log.info("MainActivity已注册，并被通知到登陆状态");
			userName.setClickable(false);
			isLogin = true;
			String id = UserManager.getInstance().getUserName();
			userName.setText(id);
		} else {
			isLogin = false;
			userName.setClickable(true);
			userName.setText("登陆");
			log.info("MainActivity已注册，并被通知到未登陆状态");
		}
	}

	/**
	 * 展示导航菜单
	 */
	@Override
	public void showMenuNavigation() {
		// hideSoft();
		mMenuDrawer.openMenu();
	}

	/**
	 * 展示登陆菜单
	 */
	@Override
	public void showMenuLogin() {

		if (!menuLogin.isShowing()) {
			menuLogin.showAtLocation(mMenuDrawer.getMenuView(), Gravity.BOTTOM,
					0, 0);
		}
	}

	private OnItemSelected onMenuLoginItemSelected = new OnItemSelected() {

		@Override
		public void onClick(int itemID) {
			switch (itemID) {
			case R.id.button_login:
				startActivity(new Intent(MainActivity.this, LoginActivity.class));
				break;
			case R.id.button_register:
				startActivity(new Intent(MainActivity.this,
						RegisterActivity.class));
				break;
			case R.id.button_cancle:
				menuLogin.dismiss();
				break;
			default:
				break;
			}

		}
	};

	private void hideSoft() {
		try {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			boolean isOpen = imm.isActive();
			if (isOpen) {
				imm.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		} catch (Exception e) {
			log.error("", e);
		}
	}

}
